package whf.framework.tools.data.export;

import java.util.List;
import java.util.Set;

import whf.framework.exception.FindException;
import whf.framework.meta.dao.ObjectDAO;
import whf.framework.meta.entity.IProperty;
import whf.framework.meta.entity.Object;
import whf.framework.meta.entity.ObjectProperty;
import whf.framework.util.StringUtils;
import whf.framework.util.Utils;

/**
 * @author wanghaifeng
 *
 */
public class ExportServiceImp implements ExportService {
	private ObjectDAO objectDAO;
	
	public void setObjectDAO(ObjectDAO dao){
		this.objectDAO = dao;
	}
	
	/* (non-Javadoc)
	 * @see whf.framework.tools.data.export.ExportService#findExportObjects()
	 */
	public List<Object> findExportObjects() throws FindException {
		// 获取所有以来对象关系
		List<DependInfo> dependInfos = Utils.newArrayList();
		List<Object> objects = this.objectDAO.findWithoutLazy("");
		for(Object obj: objects){
			Set<String> dependedClasses = Utils.newHashSet();
			Set<ObjectProperty> properties = obj.getProperties();
			for(IProperty prop: properties){
				dependedClasses.add(prop.getDataType());
			}
			dependInfos.add(new DependInfo(obj, dependedClasses));
		}
		// 排序
		List<Object> result = Utils.newArrayList();
		for(DependInfo info: dependInfos){
			int lastIndex = -1;
			for(String dependedClass: info.dependedClasses) {
				for(int i=0; i< result.size(); i++) {
					if(StringUtils.equalsIgnoreCase(dependedClass, result.get(i).getBoClassName())){
						if(lastIndex < i)
							lastIndex = i;
						break;
					}
				}
			}
			//
			result.add(lastIndex + 1, info.obj);
		}
		return result;
	}

	class DependInfo{
		Object obj;
		
		Set<String> dependedClasses;
		
		DependInfo(Object obj, Set<String> dependedClasses){
			this.dependedClasses = dependedClasses;
		}
	}
}
